/*
 *  Copyright (C) 2011 zhanxin zheng <420238970@qq.com>
 *
 *  This file is part of SandCat.
 *
 *  SandCat is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  SandCat is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with SandCat.  If not, see <http://www.gnu.org/licenses/>.
 *
 */


#include "basic.h"
#include "struct.h"
#include "struct_main_command.h"
#include "audio_interface.h"
#include "ui_interface.h"

struct key_value{
	char key[ KEY_SIZE ];
	char value[ VALUE_SIZE ];
};

//==============================================================================DATA
static pthread_mutex_t main_command_mutex;
static main_command_u *main_command;
static struct key_value *pool = NULL;
static unsigned int pool_size = 0;



int read_config_file();
int write_config_file();
void handle_C_SHUTDOWN( void );
void handle_C_CONFIG_GET( void );
void handle_C_CONFIG_SET( void );
//==============================================================================MAIN THREAD
int main( int argc, char *argv[] )
{	
	get_context(argc, argv);
  
	pthread_mutex_init( &main_command_mutex, NULL );
	main_command = (main_command_u *)malloc( sizeof(main_command_u) );
	main_command->type = C_VOID;
	main_command->fifo.next = NULL;

	pthread_t ui_thread = ui_init();
	pthread_t audio_thread = audio_init();

	read_config_file();

//------------------------------------------------------------------------------WORKFLOW
	while(1){
		{//DETECT-SIGNAL//
			if( pthread_mutex_trylock( &main_command_mutex ) != 0 ){ usleep(1000); continue; }

			switch( main_command->type ){
				case C_VOID : 	break;
				
				case C_SHUTDOWN : 	handle_C_SHUTDOWN(); break;
				
				case C_CONFIG_GET:  handle_C_CONFIG_GET(); break;

				case C_CONFIG_SET:  handle_C_CONFIG_SET(); break;
									
				default : 	break;
			}
			/*POP*/
			main_command_u *com = NULL;
			if( main_command->fifo.next == NULL ){
				main_command->type = C_VOID;
				pthread_mutex_unlock( &main_command_mutex );
			}else{
				com = main_command;
				main_command = main_command->fifo.next;
				free(com);
				pthread_mutex_unlock( &main_command_mutex );			
				continue;
			}
		}

		if( !pthread_tryjoin_np(audio_thread, (void**)NULL) )
		{											   
			write_config_file();
			fprintf( stderr, "\nMain Exit\n" );
			exit(0);
		}

		//fprintf(stderr, " main " );
		usleep(200000);
	}
//------------------------------------------------------------------------------

	return EXIT_SUCCESS;
}

//==============================================================================COMMAND INTERFACE
void main_shutdown()
{	
	pthread_mutex_lock( &main_command_mutex );
	main_command_u *command = main_command;
	while( command->fifo.next != NULL ) command = command->fifo.next;
	if( command->type == C_VOID ){
		command->type = C_SHUTDOWN;
	}else{/*PUSH*/
		command->fifo.next = (main_command_u *)malloc( sizeof(main_command_u) );
		command->fifo.next->fifo.next = NULL;
		command->fifo.next->type = C_SHUTDOWN;
	}
	pthread_mutex_unlock( &main_command_mutex );
}	

void main_config_get( const char *key, char **value )
{	
	char *_key = (char *)malloc( strlen(key)+1 );
	strcpy( _key, key );
	*value = NULL;
	
	pthread_mutex_lock( &main_command_mutex );
	main_command_u *command = main_command;
	while( command->fifo.next != NULL ) command = command->fifo.next;
	if( command->type == C_VOID ){
		command->type = C_CONFIG_GET;
		command->config_get.key = _key;
		command->config_get.value = value;
	}else{/*PUSH*/
		command->fifo.next = (main_command_u *)malloc( sizeof(main_command_u) );
		command->fifo.next->fifo.next = NULL;
		command->fifo.next->type = C_CONFIG_GET;
		command->fifo.next->config_get.key = _key;
		command->fifo.next->config_get.value = value;
	}
	pthread_mutex_unlock( &main_command_mutex );

	while( *value == NULL );
}

void main_config_set( const char *key, const char *value )
{
	char *_key = (char *)malloc( strlen(key)+1 );
	strcpy( _key, key );
	char *_value = (char *)malloc( strlen(value)+1 );
	strcpy( _value, value );
	
	pthread_mutex_lock( &main_command_mutex );
	main_command_u *command = main_command;
	while( command->fifo.next != NULL ) command = command->fifo.next;
	if( command->type == C_VOID ){
		command->type = C_CONFIG_SET;
		command->config_set.key = _key;
		command->config_set.value = _value;
	}else{/*PUSH*/
		command->fifo.next = (main_command_u *)malloc( sizeof(main_command_u) );
		command->fifo.next->fifo.next = NULL;
		command->fifo.next->type = C_CONFIG_SET;
		command->fifo.next->config_set.key = _key;
		command->fifo.next->config_set.value = _value;
	}
	pthread_mutex_unlock( &main_command_mutex );
}

//==============================================================================COMMAND HANDLER
void handle_C_SHUTDOWN( void )
{
	ui_exit();
	audio_exit();
}

void handle_C_CONFIG_GET( void )
{	
	int i = 0;
	while( strcmp( (pool+i)->key, "\0") ){
		if( !strcmp( (pool+i)->key, main_command->config_get.key) ){
			*(main_command->config_get.value) = (pool+i)->value;
			goto out;
		}else i += 1;
	}
	*(main_command->config_get.value) = "_NOTHING_";

out:
	printf( "Get Key-Value: %s -> %s\n", main_command->config_get.key, *(main_command->config_get.value) );
}

void handle_C_CONFIG_SET( void )
{
	int i = 0;
	while( strcmp( (pool+i)->key, "\0") ){
		printf( "%d: %s -> %s\n", i, (pool+i)->key, (pool+i)->value );
		if( !strcmp( (pool+i)->key, main_command->config_set.key) ){
			strcpy( (pool+i)->value, main_command->config_set.value );
			printf( "I Got It\n" );
			goto out;
		}
		i++;
	}

	if( i >= (pool_size / KEY_VALUE_SIZE) ){
		printf( "%s\n", "new a pool" );
		struct key_value *tmp = ( struct key_value* )malloc( pool_size * 2 );
		memcpy( tmp , pool, pool_size );
		pool_size = pool_size * 2;
		free( pool );
		pool = tmp;
	}
	
	strcpy( (pool+i)->key, main_command->config_set.key );
	strcpy( (pool+i)->value, main_command->config_set.value );
	strcpy( (pool+i+1)->key, "\0" );
	strcpy( (pool+i+1)->value, "\0" );	
	printf( "INSERT %d: %s -> %s\n", i, (pool+i)->key, (pool+i)->value );

out:
	printf( "Set Key-Value: %s -> %s\n", main_command->config_set.key, main_command->config_set.value );
}

//==============================================================================FUNCTION
int read_config_file()
{
	FILE *config_file = NULL;
	if( NULL == (config_file = fopen( context.cfg_file, "rb" )) ){
		if( NULL == (config_file = fopen( context.cfg_file, "wb" )) ){
			perror( "read_config_file(): " );
			exit(-1);
		}
	}

	struct stat stat;
	fstat( config_file->_fileno, &stat);
	
	if( stat.st_size == 0 ){
		pool = ( struct key_value* )malloc( sizeof(struct key_value) * 10);
		if( NULL == pool ){
			perror( "read_config_file(): " );
			exit(-1);
		}
		pool_size = sizeof(struct key_value) * 10;
		bzero( pool, pool_size );
	}else{
		pool = ( struct key_value* )malloc( stat.st_size * 2);
		if( NULL == pool ){
			perror( "read_config_file(): " );
			exit(-1);
		}
		pool_size = stat.st_size * 2;
		bzero( pool, pool_size );
		fread( pool, 1, pool_size, config_file );
	}
	
	int i=0;
	while( strcmp( (pool+i)->key, "\0") ){
		printf( "read config file : %d: %s -> %s\n", i, (pool+i)->key, (pool+i)->value );
		i++;
	}
	
	fclose( config_file );
	return EXIT_SUCCESS;
}

int write_config_file()
{
	char rm_buf[512] = "\0";
	strcpy( rm_buf, "rm -f " );
	strcat( rm_buf, context.cfg_file );
	system( rm_buf );

	FILE *config_file = NULL;
	if( NULL == (config_file = fopen(context.cfg_file, "wb")) ){
		perror( "write_config_file(): " );
		exit(-1);
	}
	
	int i = 0;
	while( strcmp( (pool+i)->key, "\0") ){
		fwrite( pool+i, sizeof(struct key_value), 1, config_file);
		printf( "write config file : %d: %s -> %s\n", i, (pool+i)->key, (pool+i)->value );
		i++;
	}
	fwrite( pool+i, sizeof(struct key_value), 1, config_file );

	fclose( config_file );	
	return EXIT_SUCCESS;
}


